package com.bozhong.robot.bar.barcounter;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.WindowManager;

import com.aruba.socketlibrary.protocol.SocketManager.HKSocketDataManager;
import com.aruba.socketlibrary.protocol.SocketManager.SocketDataManager;
import com.aruba.socketlibrary.protocol.entity.FaceChangeMessage;
import com.bozhong.robot.bar.barcounter.ui.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import pl.droidsonroids.gif.GifImageView;

public class MainActivity extends BaseActivity {

    private View main;
    private GifImageView mFaceiv;
    private static final int FACE_LEFT = 1, FACE_MIDDLE = 2, FACE_RIGHT = 3, FACE_DOING = 4, FACE_LEFT_RIGHT_DOING = 5, MUSIC_END = 0xFF;
    private MediaPlayer mMediaPlayer;
    private int mCurrentIndex; // 当前播放的音乐位置
    private static final String SEPARATOR = File.separator;//路径分隔符
    private static final String MUSIC_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + SEPARATOR + "BarCounter";
    // private static final String MUSIC_PATH = Environment.getDownloadCacheDirectory() + SEPARATOR + "BarCounter";

    private static final Uri music1 = Uri.parse("android.resource://com.bozhong.robot.bar.barcounter/" + R.raw.you);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);

        main = getLayoutInflater().inflate(R.layout.activity_main, null);
        main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE);
        setContentView(main);
        setFullScreen(true);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mFaceiv = (GifImageView) findViewById(R.id.iv_face);
//        mHandler.postDelayed(mDoRunnable, TIMES);

//        mMusicFile = new File(MUSIC_PATH);
//        if (!mMusicFile.exists()) {
//            copyFilesFromRaw(this,R.raw.intro, ".mp3",MUSIC_PATH);
//            copyFilesFromRaw(this,R.raw.a_little_story, "a_little_story.mp3",MUSIC_PATH);
//        }

        findViewById(R.id.btn_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                faceSwitch(FACE_LEFT);
                playMusic();
            }
        });

        findViewById(R.id.btn_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                faceSwitch(FACE_RIGHT);
            }
        });

        findViewById(R.id.btn_doing).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                faceSwitch(FACE_DOING);
            }
        });

        findViewById(R.id.btn_middle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                faceSwitch(MUSIC_END);
                stopMusic();
            }
        });

        initSocket();
    }

    private SocketDataManager socketDataManager;

    private void initSocket() {
        socketDataManager = new SocketDataManager.Builder(getApplicationContext())
                .deviceConfig("192.168.222.10", 50009)
                .loadClass(HKSocketDataManager.class)
                .build();

        socketDataManager.open();

        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(FaceChangeMessage messageEvent) {
        faceSwitch(messageEvent.flag);
    }


    /**
     * 根据不同动作标识，设置对应的显示
     *
     * @param face
     */
    private void faceSwitch(int face) {
        if (FACE_LEFT == face) {
            playMusic();
            mFaceiv.setImageResource(R.drawable.face_left);
        } else if (FACE_MIDDLE == face) {
            playMusic();
            mFaceiv.setImageResource(R.drawable.face_middle);
        } else if (FACE_RIGHT == face) {
            playMusic();
            mFaceiv.setImageResource(R.drawable.face_right);
        } else if (FACE_DOING == face) {
            mFaceiv.setImageResource(R.drawable.face_doing);
        } else if (FACE_LEFT_RIGHT_DOING == face) {
            playMusic();
            mFaceiv.setImageResource(R.drawable.face_left_right_doing);
        } else if (MUSIC_END == face) {
            mFaceiv.setImageResource(R.drawable.face_doing);
            stopMusic();
        }
    }

    @Override
    protected void onDestroy() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }

        socketDataManager.stop();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void stopMusic() {
        // 暂停播放
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    /**
     * 设置是否全屏
     *
     * @param enable
     */
    private void setFullScreen(boolean enable) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        if (enable) {
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        } else {
            lp.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        getWindow().setAttributes(lp);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

    private String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }


    /**
     * 播放音乐
     */
    private void playMusic() {
//        if (mSubMusicFiles == null) {
//            mSubMusicFiles = mMusicFile.listFiles();
//        }
//        if (mSubMusicFiles == null || mSubMusicFiles.length == 0) {
//            return;
//        }
//
//        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
//            return;
//        }

        try {
            if (mMediaPlayer == null) {
                mMediaPlayer = new MediaPlayer();
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setLooping(true);
                mMediaPlayer.setDataSource(this, music1);
                mCurrentIndex = 0;
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 拷贝数据
     *
     * @param context
     * @param id
     * @param fileName
     * @param storagePath
     */
    public static void copyFilesFromRaw(Context context, int id, String fileName, String storagePath) {
        InputStream inputStream = context.getResources().openRawResource(id);
        File file = new File(storagePath);
        if (!file.exists()) {//如果文件夹不存在，则创建新的文件夹
            file.mkdirs();
        }
        readInputStream(storagePath + SEPARATOR + fileName, inputStream);
    }

    /**
     * 读取输入流中的数据写入输出流
     *
     * @param storagePath 目标文件路径
     * @param inputStream 输入流
     */
    public static void readInputStream(String storagePath, InputStream inputStream) {
        File file = new File(storagePath);
        try {
            if (!file.exists()) {
                // 1.建立通道对象
                FileOutputStream fos = new FileOutputStream(file);
                // 2.定义存储空间
                byte[] buffer = new byte[inputStream.available()];
                // 3.开始读文件
                int lenght = 0;
                while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
                    // 将Buffer中的数据写到outputStream对象中
                    fos.write(buffer, 0, lenght);
                }
                fos.flush();// 刷新缓冲区
                // 4.关闭流
                fos.close();
                inputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
